package com.library.controller.admin;

import com.library.dto.BookDTO;
import com.library.result.Result;
import com.library.service.BookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/admin/book")
@Slf4j
@Api(tags = "管理员书籍相关接口")
public class AdminBookController {

    @Autowired
    private BookService bookService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增书籍
     * @param bookDTO
     * @return
     */
    @PostMapping
    @ApiOperation("新增书籍")
    public Result save(@Valid @RequestBody BookDTO bookDTO) {
//        if (result.hasErrors()) {
//            // 返回验证错误信息
//            List<String> errors = result.getFieldErrors()
//                    .stream()
//                    .map(error -> error.getField() + ": " + error.getDefaultMessage())
//                    .collect(Collectors.toList());
//            return Result.error(errors.toString());
//        }
        log.info("新增书籍：{}", bookDTO);

        bookService.save(bookDTO);

        //清理缓存数据
        cleanCache("book_page_query_*");

        return Result.success();
    }

    /**
     * 修改书籍
     * @param bookDTO
     * @param id
     * @return
     */
    @PutMapping("/{id}")
    @ApiOperation("修改书籍")
    public Result update(@Valid @RequestBody BookDTO bookDTO, @PathVariable Long id) {
        log.info("修改书籍{}：{}",id, bookDTO);

        bookService.update(bookDTO,id);

        //清理缓存数据
        cleanCache("book_page_query_*");

        return Result.success();
    }

    /**
     * 根据id删除书籍
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @ApiOperation("根据id删除书籍")
    public Result deleteById(@PathVariable Long id) {
        log.info("根据id删除书籍{}",id);

        bookService.deleteById(id);

        //清理缓存数据
        cleanCache("book_page_query_*");

        return Result.success();
    }

    /**
     * 批量删除书籍
     * @param ids
     * @return
     */
    @DeleteMapping
    @ApiOperation("批量删除书籍")
    public Result deleteByIds(@RequestParam List<Long> ids) {
        log.info("批量删除书籍{}",ids);

        bookService.deleteBatch(ids);

        //清理缓存数据
        cleanCache("book_page_query_*");

        return Result.success();
    }
    /**
     * 清理缓存数据
     * @param pattern
     */
    private void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

}
